<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Sys_User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $user = Sys_User::where('username', $username)->first();
        if ($user && Hash::check($password, $user->password)){
            $token = JWTAuth::fromUser($user);
            if($token !="" || $token !=null) {
                return $this->responseSuccess([
                    'accessToken' => $token,
                    'tokenType' => 'Bearer'
                ]);
            }
            return $this->responseError(trans('auth.incorrect'));
        }
        return $this->responseError("登录失败，请重试！");
    }


    public function refreshToken(Request $request)
    {
        try {
            // 尝试通过refresh token获取新的access token
            $old_token = JWTAuth::getToken();
            $token = JWTAuth::refresh($old_token);
        } catch (TokenExpiredException $e) {
            return $this->responseError( 'Token过期 ');
        } catch (TokenInvalidException $e) {
            return $this->responseError('Token无效');
        } catch (JWTException $e) {
            return $this->responseError('Token创建失败.');
        }

        // 返回新的token
        return $this->responseSuccess([
            'accessToken' => $token,
            'tokenType' => 'Bearer'
        ]);
    }

    public function logout(Request $request)
    {
        JWTAuth::logout();
        return $this->responseSuccess([
            'accessToken'
        ]);
    }

}
